package com.accounting.client.frontend.product.handlers;

import java.util.List;

import com.accounting.client.frontend.common.CurrencyBox;
import com.accounting.client.remote.Services;
import com.accounting.client.remote.enumeration.WeightUnit;
import com.accounting.client.remote.obj.ProductCatalog;
import com.accounting.client.remote.transfer.AddProductRequest;
import com.accounting.client.session.ErrorHandler;
import com.accounting.client.session.SessionManager;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Widget;

import corelib.client.Util;
import corelib.client.delegate.Action;
import corelib.client.resource.CommonResources;
import corelib.client.ui.SimpleModal;
import corelib.client.ui.widget.Size;
import corelib.client.ui.widget.WidgetListener;
import corelib.client.ui.widget.WindowHandle;
import corelib.client.ui.widget.button.IsButton;
import corelib.client.ui.widget.dialog.SimpleDialogHandler;
import corelib.client.ui.widget.form.DecimalBox;
import corelib.client.ui.widget.form.LazyInitializer;
import corelib.client.ui.widget.form.SelectField;
import corelib.client.ui.widget.form.TextAreaField;
import corelib.client.ui.widget.form.TextField;
import corelib.client.ui.widget.form.fomatters.NullableValueFormatter;
import corelib.client.ui.widget.form.fomatters.ValueFormatter;
import corelib.client.ui.widget.layout.RelativeColumn;
import corelib.client.ui.widget.messagebox.SimpleMessageBox;

public class CreateProductHandler extends SimpleDialogHandler {
	
	private ProductCatalog catalogInfo;
	private Action action;
	
	private TextField cNameField;
	private TextAreaField  descriptionField;
	private TextField nameField;
	private TextField KeywordsField;
	private SelectField<ProductCatalog> catalogField;
	
	private CurrencyBox  priceField;
	private DecimalBox   weightField;
	private SelectField<WeightUnit> weightUnitField;
	
	public CreateProductHandler(ProductCatalog catalog, Action action) {
		this.action = action;
		this.catalogInfo = catalog;
	}
	
	@Override
	public String getHeading() {
		return "增加新的产品";
	}

	@Override
	public Size getSize() {
		return new Size(500, 500);
	}

	@Override
	public Widget getContentPanel() {
		int lw = 100;
		int fw = 300;
		int gap = 12;
		
		FlowPanel panel = new FlowPanel();
		panel.getElement().getStyle().setPadding(20, Unit.PX);
		
		RelativeColumn col = new RelativeColumn();
		if (this.catalogInfo != null){
			col.setRowSpacing(12);
			col.addRow().add(LazyInitializer.createLabel("新增加的产品 : " + catalogInfo.getCName()).setBold(true),lw + fw);
		}
		else {
			col.addRow()
			   .add(LazyInitializer.createLabel("产品类别"),lw)
			   .addSpace(gap)
			   .add(catalogField = new SelectField<ProductCatalog>(new WidgetListener(){
					@Override
					public void valueUpdated(Widget widget) {
						catalogInfo = catalogField.getSelectedOption();
					}
			   }),fw);
			
			loadCatalogs();
			catalogField.setOptionFormatter(new ValueFormatter<ProductCatalog>(){
				@Override
				public String format(ProductCatalog value) {
					return value.getCName();
				}
			});
		}
		
		col.setRowSpacing(12);
		col.addRow().add(LazyInitializer.createLabel("产品英文名"), lw)
			.addSpace(gap)
			.add(nameField = LazyInitializer.createTextBox("产品英文名"),fw);
		
		col.setRowSpacing(12);
		col.addRow()
		   .add(LazyInitializer.createLabel("产品中文名"), lw)
		   .addSpace(gap)
		   .add(cNameField = LazyInitializer.createTextBox("产品中文名"),fw);
		
		col.setRowSpacing(12);
		col.addRow()
		   .add(LazyInitializer.createLabel("主要搜索字段"), lw)
		   .addSpace(gap)
		   .add(KeywordsField = LazyInitializer.createTextBox("主要搜索字段"), fw);
		
		col.setRowSpacing(12);
		col.addRow()
		   .add(LazyInitializer.createLabel("重量"), lw)
		   .addSpace(gap)
		   .add(weightField = new DecimalBox(), 150)
		   .addSpace(gap)
		   .add(weightUnitField = LazyInitializer.createSelectBox(WeightUnit.All), fw - 150 - gap);
		
		col.setRowSpacing(12);
		col.addRow()
		   .add(LazyInitializer.createLabel("估计运输价格"), lw)
		   .addSpace(gap)
		   .add(priceField = new CurrencyBox(), fw);
		   
		col.setRowSpacing(12);
		col.addRow()
		   .add(LazyInitializer.createLabel("产品描述"), lw + fw);
		
		col.addRow()
   		   .add(descriptionField = LazyInitializer.createTextArea(), lw + gap +fw);
		descriptionField.setHeight(100);
		
		weightUnitField.setNullable(true);
		weightUnitField.setOptionFormatter(new NullableValueFormatter<WeightUnit>(){
			@Override
			protected String formatNull() {
				return "请选择重量单位";
			}
			@Override
			protected String formatNotNull(WeightUnit value) {
				return value.getCname() + "(" + value.getName() + ")";
			}
		});
		panel.add(col.getPanel());
		return panel;
	}
	
	private void loadCatalogs (){
		String passport = SessionManager.getPassport();
		Services.ProductCatalogService.GetLeafProductCatalogs(passport, 
				new AsyncCallback<List<ProductCatalog>>(){
			@Override
			public void onFailure(Throwable caught) {
			}
			@Override
			public void onSuccess(List<ProductCatalog> result) {
				catalogField.setOptions(result);
			}
		});
	}
	
	@Override
	public IsButton[] getButtons() {
		return new IsButton[]{
			   new IsButton("完成",CommonResources.INSTANCE.accept16(),new WidgetListener(){
					@Override
					public void valueUpdated(Widget widget) {
						createProduct();
					}
			   })
		};
	}

	@Override
	public void onClosing(WindowHandle windowHandle) {
		windowHandle.close();
	}
	
	private void createProduct() {
		if (catalogInfo == null){
			SimpleMessageBox.error("错误", "产品类别缺失", null);
			return;
		}
		
		if (Util.isBlank(cNameField.getTrimmedText())){
			cNameField.markRequired();
			return;
		}
		
		if (Util.isBlank(nameField.getTrimmedText())){
			nameField.markRequired();
			return;
		}
		
		if (Util.isBlank(weightField.getTrimmedText())){
			weightField.markRequired();
			return;
		}
		
		if (weightUnitField.getSelectedOption() == null){
			weightUnitField.markRequired();
			return;
		}
		
		if (Util.isBlank(descriptionField.getTrimmedValue())){
			descriptionField.markRequired();
			return;
		}
		
		if (priceField.getDouble(0.0) == 0.0){
			priceField.markRequired();
			return;
		}
		
		String passport = SessionManager.getPassport();
		AddProductRequest request = new AddProductRequest();
		request.setCatalogId(catalogInfo.getId());
		request.setCName(cNameField.getTrimmedText());
		request.setName(nameField.getTrimmedText());
		request.setDescription(descriptionField.getValue());
		request.setPrice(priceField.getDouble(0.0));
		request.setWeight(weightField.getDouble(0.0));
		request.setKeywords(Util.getString(KeywordsField.getTrimmedText()));
		request.setWeightUnit(weightUnitField.getSelectedOption().getName());
		
		SimpleModal.show("努力增加中...");
		Services.ProductService.AddProduct(passport, request, new AsyncCallback<Boolean>(){
			@Override
			public void onFailure(Throwable caught) {
				SimpleModal.hide();
				ErrorHandler.handleServiceError(caught);
			}
			
			@Override
			public void onSuccess(Boolean result) {
				SimpleModal.hide();
				if (result == Boolean.TRUE) {
					closeDialog();
					if (action != null){
						action.run();
					}
				}
			}
		});
	}
}
